import $ = require("jquery");
import artTemplate = require("artTemplate");
import { v4 as uuidv4 } from "uuid";

function Write(target: JQuery, data: any) {
    const script_template_id_dataKeyName = "data-template-content-sign-id";
    const script_template_id = target.attr(script_template_id_dataKeyName);
    if (script_template_id) {
        // 二次渲染
        let script = $(`#${script_template_id}`);
        let template_text = script.html();
        target.empty();
        target.append(artTemplate.render(template_text, data));
    } else {
        // 首次渲染
        let box: JQuery = target.clone();
        let template_text = box.html();
        box = replace_element_name(box, "div");
        box.empty();
        box.append(artTemplate.render(template_text, data));
        const script_template_id = `IDScriptTemplateHTML_${uuidv4()}`;
        box.attr(script_template_id_dataKeyName, script_template_id);
        target.replaceWith(box);
        let script = $(document.createElement("script"));
        script.attr("id", script_template_id);
        script.attr("type", "text/html");
        script.html(template_text);
        script.css({ display: "none !important" });
        $("html").append(script);
    }
}

/**
 * 替换元素名, 例如: <div>...</div> => <p>...</p>
 * https://blog.csdn.net/wei741094234/article/details/102871457
 * @param element 需被替换元素
 * @param name 目标元素名
 * @returns 被替换元素结果
 */
function replace_element_name(element: JQuery, name: string): JQuery {
    var html = element.get(0).outerHTML;
    html = html.replace(/^<[a-zA-Z]+/, `<${name}`);
    html = html.replace(/\/[a-zA-Z]+>$/, `/${name}>`);
    element.replaceWith(html);
    return element;
}
